package cn.conac.rc.user.service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.user.contsant.Contsants;
import cn.conac.rc.user.entity.OuserEntity;
import cn.conac.rc.user.entity.UserAreaEntity;
import cn.conac.rc.user.entity.UserEntity;
import cn.conac.rc.user.entity.UserExtEntity;
import cn.conac.rc.user.vo.UserInfoVo;

/**
 * UserCommonService类
 *
 * @author serviceCreator
 * @date 2017-04-11
 * @version 1.0
 */
@Service
@Transactional
public class UserCommService {
	
	@Autowired
	private UserService userService;

	@Autowired
	private OuserService ouserService;

	@Autowired
	private UserAreaService userAreaService;
	
	@Autowired
	private UserExtService userExtService;
	
	/**
	 *  保存用户信息
	 * @param userInfoVo
	 * @return  用户ID
	 */
	public Map<String, String> SaveUserInfo(UserInfoVo userInfoVo) {
		
		Map<String, String> resultMap = new HashMap<String, String>();
		Integer userId  = null;
		// 用户私密信息的更新
		OuserEntity ouserEntity = userInfoVo.getOuserEntity();	
		if(null != ouserEntity) {
			if(StringUtils.isBlank(ouserEntity.getUsername())){
				ouserEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX);
			}
			ouserService.save(ouserEntity);
			userId  = ouserEntity.getUserId();
			if(null != userId) {
				resultMap.put("userId", userId.toString());
			} else  {
				resultMap.put("userId", null);
				return resultMap;
			}
		}
		
		// 用户信息的保存
		UserEntity userEntity = userInfoVo.getUserEntity();
		if(null != userEntity) {
			// 设置用户ID
			userEntity.setUserId(userId);
//			StringBuffer sbRoleNames = new StringBuffer();
//			// 设置RoleNames（冗余字段便于查询） 
//			List<RoleEntity> roleList = userEntity.getRoleList();
//			int cnt = 0; 
//			for (RoleEntity roleEntity: roleList) {
//				sbRoleNames.append(roleEntity.getRoleName());
//				if(cnt != roleList.size()-1) {
//					sbRoleNames.append(Contsants.SEMICOLON_FLAG);
//				}
//			}
//			userEntity.setRoleNames(sbRoleNames.toString());
			// 老版系统使用防止被篡改，此处在设置一次
			userEntity.setIsAdmin(1);
			if(StringUtils.isBlank(userEntity.getUsername()) && null != userId ) {
				userEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX + userId.toString());
				//再次更新icpo_user中的username
				ouserEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX+ userId.toString());
				ouserService.save(ouserEntity);
			}
			userService.save(userEntity);
		}
		
		// 用户扩展信息的保存
		UserExtEntity userExtEntity = userInfoVo.getUserExtEntity();
		if(null != userExtEntity) {
			// 设置用户ID
			userExtEntity.setUserId(userId);
			userExtService.save(userExtEntity);
		}
		
		// 用户区域信息的保存
		UserAreaEntity userAreaEntity = userInfoVo.getUserAreaEntity();
		if(null != userAreaEntity) {
			// 设置用户ID
			userAreaEntity.setUserId(userId);
			userAreaService.save(userAreaEntity);
			resultMap.put("userAreaId", userAreaEntity.getId().toString());
		}
		
		return resultMap;
	}
	
	/**
	 *  更新用户信息
	 * @param userInfoVo
	 * @return  用户ID
	 * @throws IllegalAccessException 
	 * @throws InvocationTargetException 
	 */
	public Map<String, String> UpdateUserInfo(Integer userId, UserInfoVo userInfoVo) throws InvocationTargetException, IllegalAccessException {
		
		Map<String, String> resultMap = new HashMap<String, String>();
		// 用户私密信息的更新
		OuserEntity ouserEntity = userInfoVo.getOuserEntity();
		if(null != ouserEntity) {
			OuserEntity ouserEntityDb = ouserService.findById(userId);
			if(null == ouserEntityDb) {
				resultMap.put("error", "根据"+ userId.toString() + "取得【OuserEntity】的数据为null");
				return resultMap;
			}
			OuserEntity ouserEntityNew = new OuserEntity();
			BeanMapper.copy(ouserEntityDb, ouserEntityNew);
			// 将页面设置的不为null值覆盖DB中的值
			BeanMapper.copyIgnorNull(ouserEntity, ouserEntityNew);
			ouserEntityNew.setUserId(userId);
			ouserService.save(ouserEntityNew);
		}

		// 用户信息的保存
		UserEntity userEntity = userInfoVo.getUserEntity();
		if(null != userEntity) {
			UserEntity userEntityDb = userService.findById(userId);
			if(null == userEntityDb) {
				resultMap.put("error", "根据"+ userId.toString() + "取得的【UserEntity】的数据为null");
				return resultMap;
			}
			UserEntity  userEntityNew = new UserEntity();
			BeanMapper.copy(userEntityDb, userEntityNew);
			userEntityNew.setRoleList(userEntityDb.getRoleList());
			// 将页面设置的不为null值覆盖DB中的值
			BeanMapper.copyIgnorNull(userEntity, userEntityNew);
			if(null !=userEntity.getRoleList()){
				userEntityNew.setRoleList(null);
				userEntityNew.setRoleList(userEntity.getRoleList());				
			}
			
			// 设置用户ID
			userEntityNew.setUserId(userId);
			// 老版系统使用防止被篡改，此处在设置一次
			userEntityNew.setIsAdmin(1);
			userService.save(userEntityNew);
		}
		
		// 用户扩展信息的保存
		UserExtEntity userExtEntity = userInfoVo.getUserExtEntity();
		if(null != userExtEntity) {
			UserExtEntity userExtEntityDb = userExtService.findById(userId);
			if(null == userExtEntityDb) {
				resultMap.put("error", "根据"+ userId.toString() + "取得的【UserExtEntity】的数据为null");
				return resultMap;
			}
			UserExtEntity  userExtEntityNew = new UserExtEntity();
			BeanMapper.copy(userExtEntityDb, userExtEntityNew);
			// 将页面设置的不为null值覆盖DB中的值
			BeanMapper.copyIgnorNull(userExtEntity, userExtEntityNew);
			
			// 设置用户ID
			userExtEntityNew.setUserId(userId);
			userExtService.save(userExtEntityNew);
		}
		
		// 用户区域信息的保存
		UserAreaEntity userAreaEntity = userInfoVo.getUserAreaEntity();
		if(null != userAreaEntity) {
			// 设置用户ID
			UserAreaEntity userAreaEntityDb = userAreaService.findByUserId(userId);
			if(null == userAreaEntityDb) {
				resultMap.put("error", "根据"+ userId.toString() + "取得的【UserAreaEntity】的数据为null");
				return resultMap;
			}
			UserAreaEntity  userAreaEntityNew = new UserAreaEntity();
			BeanMapper.copy(userAreaEntityDb, userAreaEntityNew);
			// 将页面设置的不为null值覆盖DB中的值
			BeanMapper.copyIgnorNull(userAreaEntity, userAreaEntityNew);
			userAreaEntityNew.setUserId(userId);
			userAreaService.save(userAreaEntityNew);
		}
		
		// 设定结果返回值
		resultMap.put("userId", userId.toString());
		
		return resultMap;
	}
	
	/**
	 *  保存用户信息
	 * @param userInfoVo
	 * @return  用户ID
	 * @throws Exception 
	 */
	public Map<String, String> SaveUserInfoList(List<UserInfoVo> userInfoVoList) throws Exception {
		
		Map<String, String> resultMap = new HashMap<String, String>();
		Integer userId  = null;
		int cnt = 0;
		for(UserInfoVo userInfoVo : userInfoVoList) {
			// 用户私密信息的更新
			OuserEntity ouserEntity = userInfoVo.getOuserEntity();	
			if(null != ouserEntity) {
				if(StringUtils.isBlank(ouserEntity.getUsername())){
					ouserEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX);
				}
				ouserService.save(ouserEntity);
				userId  = ouserEntity.getUserId();
				if(null == userId) {
					resultMap.put("error", "通过sequence生成userId失败");
					return resultMap;
				} 
			}
			
			// 用户信息的保存
			UserEntity userEntity = userInfoVo.getUserEntity();
			if(null != userEntity) {
				// 设置用户ID
				userEntity.setUserId(userId);
				// 老版系统使用防止被篡改，此处在设置一次
				userEntity.setIsAdmin(1);
				if(StringUtils.isBlank(userEntity.getUsername()) && null != userId ) {
					userEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX + userId.toString());
					//再次更新icpo_user中的username
					ouserEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX + userId.toString());
					ouserService.save(ouserEntity);
				}
				userService.save(userEntity);
			}
			
			// 用户扩展信息的保存
			UserExtEntity userExtEntity = userInfoVo.getUserExtEntity();
			if(null != userExtEntity) {
				// 设置用户ID
				userExtEntity.setUserId(userId);
				userExtService.save(userExtEntity);
			}
			
			// 用户区域信息的保存
			UserAreaEntity userAreaEntity = userInfoVo.getUserAreaEntity();
			if(null != userAreaEntity) {
				// 设置用户ID
				userAreaEntity.setUserId(userId);
				userAreaService.save(userAreaEntity);
			}
			cnt++;
		}
		
		resultMap.put("cnt", String.valueOf(cnt));
		
		return resultMap;
	}
	
	/**
	 *  更新用户信息
	 * @param userInfoVo
	 * @return  用户ID
	 * @throws IllegalAccessException 
	 * @throws InvocationTargetException 
	 */
	public Map<String, String> SaveOrUpdateUserInfoList(List<UserInfoVo> userInfoVoList) throws Exception  {
		
		Map<String, String> resultMap = new HashMap<String, String>();
		if(null == userInfoVoList) {
			resultMap.put("errInfo", "批量保存或更新用户信息的参数为null");
			return resultMap;
		}
		Integer userId = null;
		OuserEntity ouserEntityDb = null;
		UserExtEntity userExtEntityDb = null;
		UserAreaEntity userAreaEntityDb = null;
		UserEntity userEntityDb  = null;
		Integer cnt = 0;
		for(UserInfoVo userInfoVo : userInfoVoList) {
			// 用户私密信息的更新
			OuserEntity ouserEntity = userInfoVo.getOuserEntity();
			if(null != ouserEntity) {
				if(null != ouserEntity.getUserId()) {
					ouserEntityDb = null;
					ouserEntityDb = ouserService.findById(ouserEntity.getUserId());
					if(null == ouserEntityDb) {
						resultMap.put("errInfo", "根据"+ ouserEntity.getUserId().toString() + "取得【OuserEntity】的数据为null");
						return resultMap;
					}
					OuserEntity ouserEntityNew = new OuserEntity();
					BeanMapper.copy(ouserEntityDb, ouserEntityNew);
					// 将页面设置的不为null值覆盖DB中的值
					BeanMapper.copyIgnorNull(ouserEntity, ouserEntityNew);
					ouserService.save(ouserEntityNew);
				} else {
					userId = null;
					if(StringUtils.isBlank(ouserEntity.getUsername())){
						ouserEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX);
					}
					ouserService.save(ouserEntity);
					userId  = ouserEntity.getUserId();
					if(null == userId) {
						resultMap.put("errInfo", "通过sequence生成userId失败");
						return resultMap;
					} 
				}
			}
	
			// 用户信息的保存
			UserEntity userEntity = userInfoVo.getUserEntity();
			if(null != userEntity) {
				if(null != userEntity.getUserId()) {
					userEntityDb = null;
					userEntityDb = userService.findById(userId);
					if(null == userEntityDb) {
						resultMap.put("errInfo", "根据"+ userId.toString() + "取得的【UserEntity】的数据为null");
						return resultMap;
					}
					UserEntity  userEntityNew = new UserEntity();
					BeanMapper.copy(userEntityDb, userEntityNew);
					userEntityNew.setRoleList(userEntityDb.getRoleList());
					// 将页面设置的不为null值覆盖DB中的值
					BeanMapper.copyIgnorNull(userEntity, userEntityNew);
					if(null !=userEntity.getRoleList()){
						userEntityNew.setRoleList(null);
						userEntityNew.setRoleList(userEntity.getRoleList());				
					}
					
					// 设置用户ID
					userEntityNew.setUserId(userId);
					// 老版系统使用防止被篡改，此处在设置一次
					userEntityNew.setIsAdmin(1);
					userService.save(userEntityNew);
				} else {
					// 设置用户ID
					userEntity.setUserId(userId);
					// 老版系统使用防止被篡改，此处在设置一次
					userEntity.setIsAdmin(1);
					if(StringUtils.isBlank(userEntity.getUsername()) && null != userId ) {
						userEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX + userId.toString());
						//再次更新icpo_user中的username
						ouserEntity.setUsername(Contsants.DEFAULT_USER_NAME_PREFIX + userId.toString());
						ouserService.save(ouserEntity);
					}
					userService.save(userEntity);
				}
			}
			
			// 用户扩展信息的保存
			UserExtEntity userExtEntity = userInfoVo.getUserExtEntity();
			if(null != userExtEntity) {
				if(null != userExtEntity.getUserId()) {
					userExtEntityDb = null;
					userExtEntityDb = userExtService.findById(userId);
					if(null == userExtEntityDb) {
						resultMap.put("errInfo", "根据"+ userId.toString() + "取得的【UserExtEntity】的数据为null");
						return resultMap;
					}
					UserExtEntity  userExtEntityNew = new UserExtEntity();
					BeanMapper.copy(userExtEntityDb, userExtEntityNew);
					// 将页面设置的不为null值覆盖DB中的值
					BeanMapper.copyIgnorNull(userExtEntity, userExtEntityNew);
					
					// 设置用户ID
					userExtEntityNew.setUserId(userId);
					userExtService.save(userExtEntityNew);
				} else {
					// 设置用户ID
					userExtEntity.setUserId(userId);
					userExtService.save(userExtEntity);
				}
			}
			
			// 用户区域信息的保存
			UserAreaEntity userAreaEntity = userInfoVo.getUserAreaEntity();
			if(null != userAreaEntity) {
				if(null != userAreaEntity.getUserId()) {
					// 设置用户ID
					userAreaEntityDb = null;
					userAreaEntityDb = userAreaService.findByUserId(userId);
					if(null == userAreaEntityDb) {
						resultMap.put("errInfo", "根据"+ userId.toString() + "取得的【UserAreaEntity】的数据为null");
						return resultMap;
					}
					UserAreaEntity  userAreaEntityNew = new UserAreaEntity();
					BeanMapper.copy(userAreaEntityDb, userAreaEntityNew);
					// 将页面设置的不为null值覆盖DB中的值
					BeanMapper.copyIgnorNull(userAreaEntity, userAreaEntityNew);
					userAreaEntityNew.setUserId(userId);
					userAreaService.save(userAreaEntityNew);
				} else {
					// 设置用户ID
					userAreaEntity.setUserId(userId);
					userAreaService.save(userAreaEntity);
				}
			}
			cnt++;
		}
		
		// 设定结果返回值
		resultMap.put("cnt", cnt.toString());
		
		return resultMap;
	}
}
